package com.xiangshizhineng.tianzhangzhi.app.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiangshizhineng.tianzhangzhi.app.common.R;
import com.xiangshizhineng.tianzhangzhi.app.common.base.BaseController;
import com.xiangshizhineng.tianzhangzhi.app.config.Sender;
import com.xiangshizhineng.tianzhangzhi.app.filter.AppToken;
import com.xiangshizhineng.tianzhangzhi.app.model.response.*;
import com.xiangshizhineng.tianzhangzhi.app.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/tNE")
@Slf4j
@Api(tags = "首页")
public class TNEController extends BaseController {
    @Autowired
    private TaskService taskService;

    @Autowired
    private EventService eventService;

    @Autowired
    private NoticeService noticeService;

    @Autowired
    private UserService userService;

    @Autowired
    private DistrictService districtService;

    @Resource
    private Sender sender;

    @ApiOperation(value = "首页公告事件任务", notes = "查询所有公告，催办任务，催办事件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "s", value = "每页的条数", paramType = "query"),
            @ApiImplicitParam(name = "p", value = "请求的页码", paramType = "query"),
            @ApiImplicitParam(name = "userId", value = "当前用户id", dataType = "Long", paramType = "query", required = true),
            @ApiImplicitParam(name = "type", value = "列表类型(1公告,2任务,3事件)", dataType = "int", paramType = "query", required = true)
    })
    @GetMapping("/tNESelect")
    @Transactional(rollbackFor = Exception.class)
    @AppToken
    public R<Page> tNESelect(@RequestParam(value = "s",required = false,defaultValue = "5")Long s,
                             @RequestParam(value = "p",required = false,defaultValue = "1")Long p,
                             @RequestParam(value = "userId",required = false)String userId,
                             @RequestParam(value = "type",required = false)String type
                             ) {
        Page res = null;
        UserResponse user = userService.getOne(new QueryWrapper<UserResponse>().select("xzqdm","tzjb").eq("id", userId));
        String tzjb = null;
        String xzqdm = null;
        try {
            tzjb = user.getTzjb();
            xzqdm = user.getXzqdm();
        } catch (Exception e) {
            return R.fail("未查到此用户");
        }
        //公告
        if ("1".equals(type)) {
            res =noticeService.page(new Page<NoticeResponse>(p,s),new QueryWrapper<NoticeResponse>().
                    select("id","title","create_time","notice_type","is_banner","create_person","content","notice_status").
                    le("start_date",new Date()).gt("end_date",new Date()).orderByDesc("create_time"));
            return R.success(res);
        }
        DistrictResponse districtResponse = districtService.getOne(new QueryWrapper<DistrictResponse>().select("level","id").eq("code",xzqdm));
        String level = districtResponse.getLevel();
        Long id = districtResponse.getId();
        List<DistrictResponse> disList = districtService.list(new QueryWrapper<DistrictResponse>().select("code").eq("pid",id));
        List<String> idsCodeList = new ArrayList<>();
        disList.stream().forEach(t->{
            idsCodeList.add(t.getCode());
        });
        //任务
        if ("2".equals(type)) {
            if("3".equals(level)){
                res = (Page) taskService.selectCbByMyWrapper(new Page<TaskResponse>(p,s),new QueryWrapper<TaskResponse>().select("t.task_name","t.task_s_time","t.task_e_time","t.task_status_id","t.cb","t.id")
                        .eq("cb","1").eq("xzqhdm",xzqdm).isNull("task_xcr").
                        orderByDesc("update_time"));
            }else{
                res = (Page) taskService.selectCbByMyWrapper(new Page<TaskResponse>(p,s),new QueryWrapper<TaskResponse>().select("t.task_name","t.task_s_time","t.task_e_time","t.task_status_id","t.cb","t.id")
                        .eq("cb","1").in("xzqhdm",idsCodeList).isNull("task_xcr").
                        orderByDesc("update_time"));            }
            return R.success(res);
        }
        //事件
        if ("3".equals(type)) {
            //二级田长待办事件
            if("2".equals(tzjb)||"1".equals(tzjb)){
                List<UserResponse> userList = userService.list(new QueryWrapper<UserResponse>().select("id").in("xzqdm",idsCodeList));
                res = eventService.page(new Page<EventResponse>(p,s),new QueryWrapper<EventResponse>().
                        select("id","event_name","event_status_id","cb","create_time").eq("reviewer",userId).
                        in("event_status_id","10").orderByDesc("update_time"));
                return R.success(res);
            }
            //三级田长催办事件
            if("3".equals(tzjb)||"4".equals(tzjb)){
                res = eventService.page(new Page<EventResponse>(p,s),new QueryWrapper<EventResponse>().
                        select("id","event_name","event_status_id","cb","create_time").eq("cb","1").
                        eq("handler",userId).eq("event_status_id","11").orderByDesc("cb"));
                return R.success(res);
            }
            return R.success(null);
        }
        return R.success(null);
    }

    @ApiOperation(value = "首页轮播图列表", notes = "返回所有需要轮播的图片url")
    @GetMapping("/tNEPics")
    @AppToken
    public R<List<NoticeResponse>> tNEPics() {
        List<NoticeResponse> pics = noticeService.list(new QueryWrapper<NoticeResponse>()
                .lambda()
                .select(NoticeResponse::getId,NoticeResponse::getFilePath)
                .le(NoticeResponse::getStartDate,new Date())
                .ge(NoticeResponse::getEndDate,new Date())
                .eq(NoticeResponse::getIsBanner,"1"));
        return R.success(pics);
    }
}
